package com.liang.subject.domain.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

@Component
public class CacheUtils<V> {

    private final Cache<String, String> localCache = CacheBuilder.newBuilder()
            .maximumSize(5000)
            .expireAfterWrite(10, TimeUnit.MINUTES)
            .build();

    public List<V> getContent(String key, Class<V> clazz, Function<String, List<V>> function) {
        String content = localCache.getIfPresent(key);
        if (StrUtil.isNotBlank(content)) {
            return JSONUtil.toList(content, clazz);
        }
        List<V> resultList = function.apply(key);
        localCache.put(key, JSONUtil.toJsonStr(resultList));
        return resultList;
    }
}
